<template>
  <div class="left-menu">
    <div
      class="logo-wrap"
      @click="goHome"
    >
      <!-- 此处为版权标识，严禁删改 -->
      <img :src="logo" class="App-logo" alt="logo" />
    </div>

    <div class="menu-box">
      <a-menu
        :selectedKeys="selectedKeys"
        :openKeys="openKeys"
        mode="inline"
        style="width: 200px; background: #fff"
        @openChange="onOpenChange"
        @select="onSelect"
      >
        <template v-for="menu in activeMenus" :key="menu.key">
          <a-sub-menu v-if="menu.children && menu.children.length" :key="menu.key">
            <template #title>
              <i v-if="menu.iconClass" :class="menu.iconClass" />
              <span>{{ menu.label }}</span>
            </template>

            <a-menu-item
              v-for="child in menu.children"
              :key="child.key"
              @click="onClick(child.key)"
            >
              <i v-if="child.iconClass" :class="child.iconClass" />
              <span>{{ child.label }}</span>
            </a-menu-item>
          </a-sub-menu>

          <a-menu-item v-else :key="menu.key" @click="onClick(menu.key)">
            <i v-if="menu.iconClass" :class="menu.iconClass" />
            <span>{{ menu.label }}</span>
          </a-menu-item>
        </template>
      </a-menu>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store'
import logo from '@/assets/logo.png'

type MenuItem = {
  label: string
  key: string
  iconClass?: string
  children?: MenuItem[]
  permission?: string
}

const rawItems: MenuItem[] = [
  { label: '首页概览', key: '/dashboard', iconClass: 'iconfont icon-icon-home' },
  { label: '分类管理', key: '/resource-category', iconClass: 'iconfont icon-icon-category', permission: 'resource-category-menu' },
  {
    label: '资源管理',
    key: 'resource',
    iconClass: 'iconfont icon-icon-file',
    children: [
      { label: '视频', key: '/videos', permission: 'resource-menu' },
      { label: '图片', key: '/images', permission: 'resource-menu' },
      { label: '课件', key: '/courseware', permission: 'resource-menu' }
    ]
  },
  {
    label: '课程中心',
    key: 'courses',
    iconClass: 'iconfont icon-icon-study',
    children: [{ label: '线上课', key: '/course', permission: 'course' }]
  },
  {
    label: '学员管理',
    key: 'user',
    iconClass: 'iconfont icon-icon-user',
    children: [
      { label: '学员', key: '/member/index', permission: 'user-index' },
      { label: '部门', key: '/department', permission: 'department-cud' }
    ]
  },
  {
    label: '系统设置',
    key: 'system',
    iconClass: 'iconfont icon-icon-setting',
    children: [
      { label: '系统配置', key: '/system/config/index', permission: 'system-config' },
      { label: '管理人员', key: '/system/administrator', permission: 'admin-user-index' },
      { label: '管理日志', key: '/system/adminlog', permission: 'admin-log' }
    ]
  },
  { label: '使用许可', key: '/licensing', iconClass: 'iconfont icon-xuke' }
]

const userStore = useUserStore()
const permissions = computed(() => (userStore && (userStore.permissions ?? userStore.getPermissions ?? {})) as Record<string, any> | undefined)

// 路由/导航
const router = useRouter()
const route = useRoute()

// 用于处理子->父的自动展开
const children2Parent: Record<string, string[]> = {
  '^/video': ['resource'],
  '^/image': ['resource'],
  '^/courseware': ['resource'],
  '^/member': ['user'],
  '^/department': ['user'],
  '^/course': ['courses'],
  '^/system': ['system']
}

const hit = (pathname: string): string[] => {
  for (const p in children2Parent) {
    try {
      if (new RegExp(p).test(pathname)) return children2Parent[p] ?? []
    } catch {
      // ignore
      if (pathname.indexOf(p) >= 0) return children2Parent[p] ?? []
    }
  }
  return []
}

const openKeyMerge = (pathname: string, currentOpenKeys: string[]) => {
  const newOpen = hit(pathname)
  const merged = [...newOpen]
  currentOpenKeys.forEach(k => { if (!merged.includes(k)) merged.push(k) })
  return merged
}

// 选中 / 展开 keys
const selectedKeys = ref<string[]>([route.path || '/'])
const openKeys = ref<string[]>(hit(route.path || '/'))

// 根据权限过滤菜单（返回新数组，不修改 rawItems）
function filterByPermission(items: MenuItem[], perms: Record<string, any> | undefined) {
  if (!perms || Object.keys(perms).length === 0) {
    return items;
  }

  const out: MenuItem[] = []
  for (const it of items) {
    if (!it.children || it.children.length === 0) {
      if (!it.permission || perms[it.permission] !== undefined) out.push({ ...it })
      continue
    }
    const children = it.children.filter(ch => !ch.permission || perms[ch.permission] !== undefined)
    if (children.length > 0) out.push({ ...it, children })
  }
  return out
}

const activeMenus = computed<MenuItem[]>(() => {
  return filterByPermission(rawItems, permissions.value)
})

// 跳转
const onClick = (key: string) => {
  if (!key) return
  router.push(key).catch(() => {})
}

// a-menu select / open handlers
const onSelect = (info: any) => {
  let keys: string[] = []
  if (info.selectedKeys && Array.isArray(info.selectedKeys)) {
    keys = info.selectedKeys
  } else if (info.key) {
    keys = [info.key]
  }
  selectedKeys.value = keys.length ? keys : selectedKeys.value
}

const onOpenChange = (keys: string[]) => {
  openKeys.value = keys ?? []
}

// 点击 logo 回首页
const goHome = () => {
  router.push('/').catch(() => {})
}

// 监听 route 改变
watch(() => route.path, (newPath) => {
  if (!newPath) return
  if (newPath.indexOf('/course/user') !== -1) {
    selectedKeys.value = ['/course']
    openKeys.value = openKeyMerge('/course', openKeys.value)
  } else if (newPath.indexOf('/member/learn') !== -1) {
    selectedKeys.value = ['/member/index']
    openKeys.value = openKeyMerge('/member/index', openKeys.value)
  } else {
    selectedKeys.value = [newPath]
    openKeys.value = openKeyMerge(newPath, openKeys.value)
  }
}, { immediate: true })
</script>

<style lang="less" scoped>
.left-menu {
  width: 200px;
  height: 100%;
  background-color: #fff;
  display: flex;
  flex-direction: column;

  .logo-wrap {
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 16px 0;
    background-color: #fff;
  }

  .App-logo {
    width: 124px;
    height: 40px;
  }

  .menu-box {
    width: 200px;
    height: calc(100% - 74px);
    overflow-y: auto;
    overflow-x: hidden;

    :deep(.ant-menu-item),
    :deep(.ant-menu-submenu-title) {
      height: 48px;
      line-height: 48px;
      padding: 0 20px;
      font-size: 14px;
      font-weight: 500;
      color: #666;
      display: flex;
      align-items: center;

      i {
        font-size: 18px;
        margin-right: 12px;
      }
    }

    :deep(.ant-menu-item-selected) {
      background-color: #ff4d4f !important;
      color: #fff !important;
      border-radius: 4px;

      i {
        color: #fff !important;
      }
    }

    :deep(.ant-menu-submenu-title) {
      border-radius: 4px;
      &:hover {
        background-color: #f5f5f5;
      }
    }

    :deep(.ant-menu-submenu-arrow) {
      right: 16px;
    }
  }
}

</style>
